package com.mall.malllibrary.net

import android.content.Context
import com.mall.malllibrary.net.callback.IComplete
import com.mall.malllibrary.net.callback.IError
import com.mall.malllibrary.net.callback.IFailure
import com.mall.malllibrary.net.callback.IRequest
import com.mall.malllibrary.net.callback.ISuccess
import com.mall.malllibrary.net.callback.RequestCallbacks
import com.mall.malllibrary.ui.loader.LoaderStyle
import com.mall.malllibrary.ui.loader.MallLoader
import retrofit2.Call
import retrofit2.Callback
import java.util.WeakHashMap

// 暴露给对外使用的客户端，外界调用请求直接使用RestClient
class RestClient (
    private val url:String?,
    private val request: IRequest?,
    private val success: ISuccess?,
    private val failure: IFailure?,
    private val error: IError?,
    private val complete: IComplete?,
    private val  params:WeakHashMap<String, Any>?,
    private val context: Context?,
    private val loaderStyle: LoaderStyle?,
) {
    // 伴生对象，类可以直接调用，类似类的内部静态变量
    companion object {
        fun builder():RestClientBuilder{
            return RestClientBuilder()
        }
    }

    //
    private fun request(method: HttpMethod){
        // 获取restrofit的实例
        val service = RestCreator.restService
        val call:Call<String>?
        request?.onRequestStart()
        // 请求之前显示loading
        if (loaderStyle!=null){
            MallLoader.showLoading(context, loaderStyle)
        }
        call = when(method){
            HttpMethod.GET -> service.get(url, params)
            HttpMethod.POST -> service.post(url, params)
            HttpMethod.PUT -> service.put(url, params)
            HttpMethod.DELETE -> service.delete(url, params)


            HttpMethod.UPLOAD -> TODO()
            HttpMethod.DOWNLOAD -> TODO()
        }
        call.enqueue(requestCallback)
    }

    // 回调方法
    private val requestCallback:Callback<String>
        get() = RequestCallbacks(success, failure, error, complete, request, loaderStyle)

    // 对外接口
    fun get(){
        request(HttpMethod.GET)
    }
    fun post(){
        request(HttpMethod.POST)
    }
    fun put(){
        request(HttpMethod.PUT)
    }
    fun delete(){
        request(HttpMethod.DELETE)
    }
}
